package src.week2;
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Stack;

public class ArrayStack<T> implements StackADT<T> {
    private final int DEFAULT_CAPACITY = 100;
    private int top;
    private T[] stack;

    public ArrayStack(){
        top=0;
        stack=(T[])(new Object[DEFAULT_CAPACITY]);
    }


    @Override
    public void push(T element) {
        if (size() == stack.length)
            expandCapacity();
        stack[top] = element;
        top++;
    }
    private void expandCapacity(){
        stack=Arrays.copyOf(stack, stack.length*2);
    }

    @Override
    public T pop() {
        if(isEmpty())
            throw new EmptyCollectionException("Stack");
        top--;
        T result = stack[top];
        stack[top] = null;
        return result;

    }

    @Override
    public T peek() {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");
        return stack[top-1];
    }

    @Override
    public boolean isEmpty() {
        if (top==0)
            return true;
        else
            return false;
    }


    @Override
    public int size() {
        return top;
    }

    @Override
    public String toString() {
        String result = "";
        for (int i = 0; i < size() ; i++) {
            result += stack[i];
        }
        return result;
    }
}
